<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'form/gform_ctrl_with_obj.class.php');

require_once('sitemap_entry_form.class.php');
require_once('sitemap_entry_form_view.class.php');

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/sitemap/tcms_sitemap_entry_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/settings/tcms_settings_sitemap_dbc.class.php');


class Sitemap_Entry_Form_Ctrl extends GForm_Ctrl_With_Object {
	private $htdocs_dir;

	function __construct($system_name, Vars_Manager $vm, DB_Connection $dbc, $object_id_capture = 'obj_id', $htdocs_dir) {
		$this->htdocs_dir = tangra_normalize_path($htdocs_dir);
		parent::__construct($system_name, $vm, $dbc, $object_id_capture);
		$this->export('htdocs_dir', $this->htdocs_dir);
	}

	protected function create_form() {
		$form = new sitemap_entry_Form();

//		$form->generate_html();
		return $form;
	}


	protected function create_form_view() {
		$ret = new Sitemap_Entry_Form_View($this->form);

		return $ret;
	}


	protected function on_good_submit() {
		$ret = true;

		$dbc = $this->get_dbc();
		$object = $this->get_object();
		$path = trim($this->form->get_field_value('path'));

		if (!TCMS_Sitemap_Entry_DBC::is_unique_path($dbc, $path, $object->get_id())) {
			$this->form->set_field_error('path', 'duplicate_path');
			$this->export('path', $path);
			$ret = false;
		} else {
			if (!$this->form->get_field_value('ignore')) {
				if (!file_exists($this->htdocs_dir.$path)) {
					$this->form->set_field_error('path', 'invalid_path');
					$this->export('path', $path);
					$ret = false;
				}
			}
		}


		return $ret;
	}


	protected function on_bad_submit() {

//		printbr('lajna');
	}


	protected function create_object() {
		$object = new TCMS_sitemap_entry_DBC();

		$dbc = $this->get_dbc();
		$settings_sitemap = new TCMS_Settings_Sitemap_DBC();
		$settings_sitemap->load_by_id($dbc, 1);

		$object->set_weight($settings_sitemap->get_weight());
		$object->set_change_freq($settings_sitemap->get_change_freq());

		return $object;
	}


	protected function transfer_obj2form() {
		$object = $this->get_object();
		$form = $this->get_form();

		$form->set_field_value('path', $object->get_path());
		$form->set_field_value('weight', (string)($object->get_weight() / 10));
		$form->set_field_value('change_freq', $object->get_change_freq());
	}


	protected function transfer_form2obj() {
		$object = $this->get_object();
		$form = $this->get_form();

		$object->set_path(trim($form->get_field_value('path')));
		$object->set_weight($form->get_field_value('weight') * 10);
		$object->set_change_freq($form->get_field_value('change_freq'));
	}
}